import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:roundcheckbox/roundcheckbox.dart';
import 'package:taonile/entity/user_info_entity.dart';
import 'package:taonile/routers/routers.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../config/config.dart';
import '../http/api.dart';
import '../http/web_path.dart';
import '../provider/userinfo_provider.dart';
import '../utils/count_down_time_util.dart';
import '../utils/string_utils.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({Key? key}) : super(key: key);

  @override
  State<RegisterPage> createState() => _RegisterState();
}

class _RegisterState extends State<RegisterPage> {
  String _name = "";
  String _password = "";

  // String _repassword = '';
  String _mobile = "";
  String _captcha = "";
  String _inviter_account = "";
  String _node_account = "";

  bool check = true;
  bool isHidePwd = true;

  String codeTips = '获取验证码';
  bool isGetCode = true;

  PackageInfo packageInfo = PackageInfo(appName: '', packageName: '', version: '', buildNumber: '');

  @override
  void initState() {
    super.initState();
    // getPrivacyAgreement();
    getAppInfo();
  }

  getAppInfo() async {
    packageInfo = await PackageInfo.fromPlatform();
    setState(() {});
  }

  sendSms(String mobile) async {
    if (mobile.length < 11) {
      return;
    }
    dynamic result = await Api.sendSms({'mobile': mobile});
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast("验证码已发送，请注意查看短信");
    }
  }

  register() async {
    FocusManager.instance.primaryFocus?.unfocus();
    if (_mobile.length < 11) {
      EasyLoading.showToast("请输入正确的手机号");
      return;
    }
    if (_captcha.isEmpty) {
      EasyLoading.showToast("请输入验证码");
      return;
    }
    if (_name.isEmpty) {
      EasyLoading.showToast("请输入用户名");
      return;
    }
    if (_password.length < 6) {
      EasyLoading.showToast("请输6-18位字母+数字密码");
      return;
    }

    if (!StringUtils.isStandardLoginPassword(_password)) {
      EasyLoading.showToast("请输6-18位字母+数字密码");
      return;
    }

    if (_inviter_account.isEmpty) {
      EasyLoading.showToast("请输入邀请人账号");
      return;
    }
    if (_node_account.isEmpty) {
      EasyLoading.showToast("请输入接点人账号");
      return;
    }

    var content = const Utf8Encoder().convert(_password);
    String md5pwd = "${md5.convert(content)}";

    dynamic result = await Api.register({
      'mobile': _mobile,
      'captcha': _captcha,
      'name': _name,
      'password': md5pwd,
      'repassword': md5pwd,
      'inviter_account': _inviter_account,
      'node_account': _node_account,
    });
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast("注册成功");
      Routes.router.pop(context);
    }
  }

  // getPrivacyAgreement() async {
  //   dynamic result = await Api.privacyAgreement();
  //   var jsonResult = jsonDecode(jsonEncode(result));
  //   if (jsonResult['code'] == 1) {
  //     privacyAgreement = jsonResult['data']['url'];
  //   }
  //   dynamic result2 = await Api.userAgreement();
  //   var jsonResult2 = jsonDecode(jsonEncode(result2));
  //   if (jsonResult2['code'] == 1) {
  //     userAgreement = jsonResult2['data']['url'];
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('注册'),
        centerTitle: true,
      ),
      body: Container(
          width: double.infinity,
          color: Config.colorBg,
          height: double.infinity,
          child: SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: Stack(
              children: [
                // Image.asset(
                //   'assets/images/login_bg.png',
                //   width: double.infinity,
                //   height: 300.w,
                //   fit: BoxFit.fill,
                // ),
                Container(
                  width: double.infinity,
                  padding: EdgeInsets.symmetric(vertical: 38.w, horizontal: 38.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        margin: EdgeInsets.only(left: 40.w, top: 0.w),
                        width: double.infinity,
                        child: Text(
                          packageInfo.appName,
                          style: TextStyle(fontSize: 60.sp, fontWeight: FontWeight.bold),
                        ),
                      ),
                      Container(
                        height: 88.w,
                        width: double.infinity,
                        margin: EdgeInsets.only(top: 50.w, left: 40.w, right: 40.w),
                        child: TextField(
                          keyboardType: TextInputType.phone,
                          textAlign: TextAlign.justify,
                          maxLength: 11,
                          maxLines: 1,
                          onChanged: (value) {
                            setState(() {
                              _mobile = value;
                            });
                          },
                          style: TextStyle(fontSize: 26.sp, color: Config.colorText1),
                          decoration: InputDecoration(
                            hintText: '请输入手机号',
                            hintStyle: const TextStyle(color: Config.colorText3),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(44.w),
                              ),
                              borderSide: const BorderSide(color: Config.colorDivider),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(44.w),
                              ),
                              borderSide: const BorderSide(color: Config.colorDivider),
                            ),
                            fillColor: Config.colorDivider,
                            filled: true,
                            counterText: '',
                            prefixIcon: Icon(
                              Icons.phone_android,
                              color: Config.colorMain,
                              size: 33.w,
                            ),
                            contentPadding: EdgeInsets.symmetric(vertical: 10.w),
                          ),
                        ),
                      ),
                      Stack(
                        children: [
                          Container(
                            height: 88.w,
                            width: double.infinity,
                            margin: EdgeInsets.only(top: 26.w, left: 40.w, right: 40.w),
                            child: TextField(
                              keyboardType: TextInputType.phone,
                              textAlign: TextAlign.justify,
                              obscureText: false,
                              maxLength: 6,
                              maxLines: 1,
                              onChanged: (value) {
                                setState(() {
                                  _captcha = value;
                                });
                              },
                              style: TextStyle(fontSize: 26.sp, color: Config.colorText1),
                              decoration: InputDecoration(
                                hintText: '请输入验证码',
                                counterText: '',
                                hintStyle: const TextStyle(color: Config.colorText3),
                                focusedBorder: OutlineInputBorder(
                                  borderRadius: BorderRadius.all(
                                    Radius.circular(44.w),
                                  ),
                                  borderSide: const BorderSide(color: Config.colorDivider),
                                ),
                                enabledBorder: OutlineInputBorder(
                                  borderRadius: BorderRadius.all(
                                    Radius.circular(44.w),
                                  ),
                                  borderSide: const BorderSide(color: Config.colorDivider),
                                ),
                                fillColor: Config.colorDivider,
                                filled: true,
                                prefixIcon: Icon(
                                  Icons.verified_user_outlined,
                                  color: Config.colorMain,
                                  size: 33.w,
                                ),
                                contentPadding: EdgeInsets.symmetric(vertical: 10.w),
                              ),
                            ),
                          ),
                          Positioned(
                            right: 60.w,
                            top: 50.w,
                            child: InkWell(
                              onTap: () {
                                if (!isGetCode) {
                                  return;
                                }
                                if (_mobile.length < 11) {
                                  EasyLoading.showToast('请输入正确的手机号码');
                                  return;
                                }
                                sendSms(_mobile);
                                CountDownTimeUtil(60, 1, (int currentTime) {
                                  var _currentTime = currentTime;
                                  setState(() {
                                    if (_currentTime == 0) {
                                      codeTips = '获取验证码';
                                      isGetCode = true;
                                    } else {
                                      codeTips = '$_currentTime';
                                    }
                                  });
                                });
                                isGetCode = false;
                              },
                              child: Text(
                                codeTips,
                                style: TextStyle(
                                  color: Config.colorMain,
                                  fontSize: 22.sp,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      Container(
                        height: 88.w,
                        width: double.infinity,
                        margin: EdgeInsets.only(top: 26.w, left: 40.w, right: 40.w),
                        child: TextField(
                          keyboardType: TextInputType.text,
                          textAlign: TextAlign.justify,
                          maxLength: 20,
                          maxLines: 1,
                          onChanged: (value) {
                            setState(() {
                              _name = value;
                            });
                          },
                          inputFormatters: [
                            //只允许输入数字和大写字母
                            FilteringTextInputFormatter.allow(RegExp("[A-Za-z0-9.@#-_]")),
                            LengthLimitingTextInputFormatter(18)
                          ],
                          style: TextStyle(fontSize: 26.sp, color: Config.colorText1),
                          decoration: InputDecoration(
                            hintText: '请输入用户名',
                            hintStyle: const TextStyle(color: Config.colorText3),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(44.w),
                              ),
                              borderSide: const BorderSide(color: Config.colorDivider),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(44.w),
                              ),
                              borderSide: const BorderSide(color: Config.colorDivider),
                            ),
                            fillColor: Config.colorDivider,
                            filled: true,
                            counterText: '',
                            prefixIcon: Icon(
                              Icons.person,
                              color: Config.colorMain,
                              size: 33.w,
                            ),
                            contentPadding: EdgeInsets.symmetric(vertical: 10.w),
                          ),
                        ),
                      ),
                      Stack(
                        children: [
                          Container(
                            height: 88.w,
                            width: double.infinity,
                            margin: EdgeInsets.only(top: 26.w, left: 40.w, right: 40.w),
                            child: TextField(
                              keyboardType: TextInputType.text,
                              textAlign: TextAlign.justify,
                              obscureText: isHidePwd,
                              maxLength: 18,
                              maxLines: 1,
                              onChanged: (value) {
                                setState(() {
                                  _password = value;
                                });
                              },
                              inputFormatters: [
                                //只允许输入数字和大写字母
                                FilteringTextInputFormatter.allow(RegExp("[A-Za-z0-9.@#-_]")),
                                LengthLimitingTextInputFormatter(18)
                              ],
                              style: TextStyle(fontSize: 26.sp, color: Config.colorText1),
                              decoration: InputDecoration(
                                hintText: '请输6-18位字母+数字密码',
                                counterText: '',
                                hintStyle: const TextStyle(color: Config.colorText3),
                                focusedBorder: OutlineInputBorder(
                                  borderRadius: BorderRadius.all(
                                    Radius.circular(44.w),
                                  ),
                                  borderSide: const BorderSide(color: Config.colorDivider),
                                ),
                                enabledBorder: OutlineInputBorder(
                                  borderRadius: BorderRadius.all(
                                    Radius.circular(44.w),
                                  ),
                                  borderSide: const BorderSide(color: Config.colorDivider),
                                ),
                                fillColor: Config.colorDivider,
                                filled: true,
                                prefixIcon: Icon(
                                  Icons.lock_outline_rounded,
                                  color: Config.colorMain,
                                  size: 33.w,
                                ),
                                contentPadding: EdgeInsets.symmetric(vertical: 10.w),
                              ),
                            ),
                          ),
                          Positioned(
                            right: 70.w,
                            top: 50.w,
                            child: InkWell(
                              onTap: () {
                                setState(() {
                                  isHidePwd = !isHidePwd;
                                });
                              },
                              child: Icon(
                                isHidePwd
                                    ? Icons.visibility_off_outlined
                                    : Icons.visibility_outlined,
                                size: 40.w,
                                color: Config.colorMain,
                              ),
                            ),
                          ),
                        ],
                      ),
                      Container(
                        height: 88.w,
                        width: double.infinity,
                        margin: EdgeInsets.only(top: 26.w, left: 40.w, right: 40.w),
                        child: TextField(
                          keyboardType: TextInputType.text,
                          textAlign: TextAlign.justify,
                          obscureText: false,
                          maxLength: 20,
                          maxLines: 1,
                          onChanged: (value) {
                            setState(() {
                              _inviter_account = value;
                            });
                          },
                          style: TextStyle(fontSize: 26.sp, color: Config.colorText1),
                          decoration: InputDecoration(
                            hintText: '请输入邀请人账号',
                            counterText: '',
                            hintStyle: const TextStyle(color: Config.colorText3),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(44.w),
                              ),
                              borderSide: const BorderSide(color: Config.colorDivider),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(44.w),
                              ),
                              borderSide: const BorderSide(color: Config.colorDivider),
                            ),
                            fillColor: Config.colorDivider,
                            filled: true,
                            prefixIcon: Icon(
                              Icons.group_add_outlined,
                              color: Config.colorMain,
                              size: 33.w,
                            ),
                            contentPadding: EdgeInsets.symmetric(vertical: 10.w),
                          ),
                        ),
                      ),
                      Container(
                        height: 88.w,
                        width: double.infinity,
                        margin: EdgeInsets.only(top: 26.w, left: 40.w, right: 40.w),
                        child: TextField(
                          keyboardType: TextInputType.text,
                          textAlign: TextAlign.justify,
                          obscureText: false,
                          maxLength: 20,
                          maxLines: 1,
                          onChanged: (value) {
                            setState(() {
                              _node_account = value;
                            });
                          },
                          style: TextStyle(fontSize: 26.sp, color: Config.colorText1),
                          decoration: InputDecoration(
                            hintText: '请输入接点人账号',
                            counterText: '',
                            hintStyle: const TextStyle(color: Config.colorText3),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(44.w),
                              ),
                              borderSide: const BorderSide(color: Config.colorDivider),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(44.w),
                              ),
                              borderSide: const BorderSide(color: Config.colorDivider),
                            ),
                            fillColor: Config.colorDivider,
                            filled: true,
                            prefixIcon: Icon(
                              Icons.link_outlined,
                              color: Config.colorMain,
                              size: 33.w,
                            ),
                            contentPadding: EdgeInsets.symmetric(vertical: 10.w),
                          ),
                        ),
                      ),
                      Container(
                        width: double.infinity,
                        height: 84.w,
                        margin: EdgeInsets.fromLTRB(40.w, 60.w, 40.w, 0),
                        child: ElevatedButton(
                          clipBehavior: Clip.antiAlias,
                          onPressed: () => register(),
                          style: ElevatedButton.styleFrom(shape: const StadiumBorder()),
                          child: const Text('立即注册'),
                        ),
                      ),
                      Container(
                        width: double.infinity,
                        height: 70.w,
                        alignment: Alignment.center,
                        margin: EdgeInsets.fromLTRB(40.w, 20.w, 40.w, 0),
                        child: InkWell(
                          onTap: () {
                            Routes.router.pop(context);
                          },
                          child: Text(
                            '已有账号登录',
                            style: TextStyle(
                                color: Config.colorMain,
                                fontSize: 30.w,
                                decoration: TextDecoration.underline),
                          ),
                        ),
                      ),
                      Container(
                          margin: EdgeInsets.only(top: 20.w),
                          width: double.infinity,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              RoundCheckBox(
                                  size: 15,
                                  checkedWidget: const Icon(
                                    Icons.check,
                                    color: Colors.white,
                                    size: 10,
                                  ),
                                  checkedColor: Config.colorMain,
                                  uncheckedColor: Config.colorBg,
                                  border: Border.all(
                                      color: check ? Config.colorMain : Config.colorText3,
                                      width: 1),
                                  isChecked: check,
                                  onTap: (selected) {
                                    check = selected!;
                                    setState(() {});
                                  }),
                              Padding(
                                padding: EdgeInsets.all(6.w),
                              ),
                              Text(
                                "我已阅读并同意",
                                style: TextStyle(
                                  color: Config.colorText2,
                                  fontSize: 26.sp,
                                ),
                              ),
                              InkWell(
                                onTap: () {
                                  Routes.navigateTo(context, Routes.webView, params: {
                                    'pageTitle': '用户协议',
                                    'webUrl': '${Config.webUrl}${WebPath.registerProtocol}'
                                  });
                                },
                                child: Text(
                                  "《用户协议》",
                                  style: TextStyle(
                                    color: Config.colorMain,
                                    fontSize: 26.sp,
                                  ),
                                ),
                              ),
                              Text(
                                "和",
                                style: TextStyle(
                                  color: Config.colorText2,
                                  fontSize: 26.sp,
                                ),
                              ),
                              InkWell(
                                onTap: () {
                                  Routes.navigateTo(context, Routes.webView, params: {
                                    'pageTitle': '隐私协议',
                                    'webUrl': '${Config.webUrl}${WebPath.privacyProtocol}'
                                  });
                                },
                                child: Text(
                                  "《隐私协议》",
                                  style: TextStyle(
                                    color: Config.colorMain,
                                    fontSize: 26.sp,
                                  ),
                                ),
                              ),
                            ],
                          )),
                    ],
                  ),
                ),
              ],
            ),
          )),
    );
  }
}
